package com.yj.springbootmybatis.service;

import com.yj.springbootmybatis.enums.Sex;
import com.yj.springbootmybatis.mapper.UserMapper;
import com.yj.springbootmybatis.pojo.User;
import com.yj.springbootmybatis.pojo.bo.UserBo;
import com.yj.springbootmybatis.util.MD5Utils;
import com.yj.springbootmybatis.util.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDate;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    private static final String DEFAULT_FACE = "https://img0.baidu.com/it/u=2919146003,3323103272&fm=26&fmt=auto&gp=0.jpg";

    @Autowired
    UserMapper userMapper;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public boolean queryUsernameIsExist(String username) {

        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("id",1);
        criteria.andEqualTo("username",username);

        User user = userMapper.selectOneByExample(example);

        return user == null ? false : true;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public User createUser(UserBo userBo) {

        User user = new User();
        user.setUsername(userBo.getUsername());
        user.setPassword(MD5Utils.md5Decode(userBo.getPassword()));
        user.setBirthday(TimeUtils.parseStr("1900-01-01")); //设置默认生日
        user.setNickname(userBo.getUsername());//默认用户昵称
        user.setFace(DEFAULT_FACE); //默认头像
        user.setSex(Sex.secret.type);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setId(UUID.randomUUID().toString().substring(0,16));

        int result = userMapper.insert(user);
        if (result > 0){
            return user;
        }else{
            return null;
        }

    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public User queryForUserLogin(String username,String password){

        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria()
                .andEqualTo("username", username)
                .andEqualTo("password", password);

        User user = userMapper.selectOneByExample(example);

        return user;
    }

}
